#include "Level1State.h"

#include <cassert>

#include <graphic/DrawManager.h>
#include <input/KeyboardState.h>
#include <main/Globals.h>
#include <main/MainConstants.h>
#include <states\GameStates.h>
#include <states/CreditsState.h>
#include <states/PresentationState.h>
#include <states/StateManager.h>
#include <utils\CharacterManager.h>
#include <utils\EnemyGenerator.h>

#include <iostream>

Level1State::Level1State() 
	: mLevelGenerator(nullptr), enemyGenerator(nullptr), level(1)
{
	LevelData level1 = {0, 2, 0, 1, 1};
	LevelData level2 = {0, 2, 0, 3, 1};
	LevelData level3 = {1, 1, 0, 4, 1};
	LevelData level4 = {1, 1, 0, 8, 1};
	LevelData level5 = {2, 1, 0, 4, 1};
	LevelData level6 = {2, 2, 0, 10, 1};

	levelData[1] = level1;
	levelData[2] = level2;
	levelData[3] = level3;
	levelData[4] = level4;
	levelData[5] = level5;
	levelData[6] = level6;
}


void Level1State::init() {
    std::cout << "Level1 init" << std::endl;

    // Create background drawable
    mBackground = new Drawable("background");
    mBackground->updatePosition(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2);
    Globals::gDrawManager->addDrawable(mBackground);

    assert(mLevelGenerator == nullptr);
    mLevelGenerator = new LevelGenerator(this);
	enemyGenerator = new EnemyGenerator(levelData[level].enemyCount, levelData[level].enemySpeed);
	enemyGenerator->generateStaticObjects(levelData[level].staticObjsCount);
	enemyGenerator->generateChilds(levelData[level].childCount, levelData[level].enemySpeed);
    Globals::gCharacterManager->init();
	level++;
}

void Level1State::update() {
    if (Globals::gKeyboardState.keyPressedEvent(SDL_SCANCODE_ESCAPE)) {
        Globals::gStateManager->changeState(*Globals::gGameStates->mCreditsState);
    }

    assert(mLevelGenerator);
    mLevelGenerator->update();
}

void Level1State::cleanEnemies() {
	delete enemyGenerator;
	enemyGenerator = nullptr;
}

void Level1State::clear() {
    //assert(mLevelGenerator);
    delete mLevelGenerator;
    mLevelGenerator = nullptr;
    Globals::gCharacterManager->clear();
	delete enemyGenerator;
    enemyGenerator = nullptr;

    Globals::gDrawManager->removeDrawable(mBackground);
    mBackground = nullptr;

    Globals::gDrawManager->clear();
}

void Level1State::rotationStart() {
	if(enemyGenerator != nullptr) {
		enemyGenerator->stopMotion();
	}	
}

void Level1State::finished() {
   clear();
   init();
}

void Level1State::rotationEnd() {
	enemyGenerator->startMotion();
}